package com.ruoyi.lm.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.lm.domain.*;
import com.ruoyi.lm.service.*;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 活动Controller
 * 
 * @author ruoyi
 * @date 2020-09-02
 */
@Controller
@RequestMapping("/lm/activityreview")
public class LmActivityReviewController extends BaseController
{
    private String prefix = "lm/activityreview";

    @Autowired
    private ILmActivityService lmActivityService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ILmUsersignService lmUsersignService;
    @Autowired
    private ILmUserService lmUserService;
    @Autowired
    private ISysDtAreaService sysDtAreaService;
    @Autowired
    private ILmMessageService lmMessageService;
    @Autowired
    private ISysUserService sysUserService;

    @RequiresPermissions("lm:activityreview:view")
    @GetMapping()
    public String activity()
    {
        return prefix + "/activityreview";
    }

    /**
     * 查询活动列表
     */
    @RequiresPermissions("lm:activityreview:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(LmActivity lmActivity)
    {
        startPage();
        lmActivity.setActivityStatus("0");
        /*lmActivity.setCreatePath("1");*/
        List<LmActivity> list = lmActivityService.selectLmActivityList(lmActivity);
        for(LmActivity temp:list){
            LmUser lmUser = lmUserService.selectLmUserById(temp.getUserId());
            //判断是PC端活动还是手机端活动，如果是手机端活动需要管理用户昵称
            if("手机发布".equals(temp.getCreatePath())){
                //手机端
                String userId = temp.getUserId();
                if(EmptyUtils.isNotEmpty(lmUserService.selectLmUserById(userId))){
                    LmUser lmUser1 = lmUserService.selectLmUserById(userId);
                    temp.setUserName(lmUser1.getUserNickname());
                    temp.setUserPhone(lmUser1.getUserPhone());
                }
            }else{
                //pc端
                temp.setUserName(temp.getUserId());
                temp.setUserPhone(sysUserService.selectUserByLoginName(temp.getUserId()).getPhonenumber());
            }
        }
        return getDataTable(list);
    }

    /**
     * 获取省
     */
    @GetMapping("/{parentId}")
    @ResponseBody
    public TableDataInfo provinceData(@PathVariable("parentId") String parentId)
    {
        SysDtArea sysDtArea = new SysDtArea();
        sysDtArea.setAreaParentId(parentId);
        List<SysDtArea> proList = sysDtAreaService.selectSysDtAreaList(sysDtArea);
        return getDataTable(proList);
    }

    /**
     * 导出活动列表
     */
    @RequiresPermissions("lm:activity:export")
    @Log(title = "活动", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(LmActivity lmActivity)
    {
        List<LmActivity> list = lmActivityService.selectLmActivityList(lmActivity);
        ExcelUtil<LmActivity> util = new ExcelUtil<LmActivity>(LmActivity.class);
        return util.exportExcel(list, "activity");
    }

    /**
     * 新增活动
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存活动
     */
    @RequiresPermissions("lm:activity:add")
    @Log(title = "活动", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam(required = false) MultipartFile[] files, LmActivity lmActivity)
    {
        lmActivity.setUserId(ShiroUtils.getSysUser().getLoginName());
        lmActivity.setCreatePath("0");
        lmActivity.setActivityStatus("2");
        lmActivity.setId(IdWorker.getId());
        try
        {
            // 上传文件路径
            String filePath = Global.getUploadPath();
            // 上传并返回新文件名称,拼接图片路径
            StringBuffer sb = new StringBuffer();
            for(int i=0;i<files.length;i++){
                String fileName = FileUploadUtils.upload(filePath, files[i]);
                String url = serverConfig.getUrl() + fileName;
                if(i == 0){
                    lmActivity.setActivityPic(url);
                }
                if(i != files.length-1){
                    sb.append(url+",");
                }else{
                    sb.append(url);
                }
            }
            lmActivity.setActivityPimages(sb.toString());
            return toAjax(lmActivityService.insertLmActivity(lmActivity));
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 修改活动
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        LmActivity lmActivity = lmActivityService.selectLmActivityById(id);
        mmap.put("lmActivity", lmActivity);
        return prefix + "/edit";
    }

    /**
     * 查看活动
     */
    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") String id, ModelMap mmap)
    {
        LmActivity lmActivity = lmActivityService.selectLmActivityById(id);
        //返回报名人数
        //获取活动报名人数
        LmUsersign lmUsersign = new LmUsersign();
        lmUsersign.setSignId(id);
        List<LmUsersign> childList = lmUsersignService.selectLmUsersignList(lmUsersign);
        lmActivity.setEnjoyNum(childList.size());
        mmap.put("lmActivity", lmActivity);
        return prefix + "/view";
    }

    /**
     * 修改保存活动
     */
    @RequiresPermissions("lm:activity:edit")
    @Log(title = "活动", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestParam(required = false) MultipartFile[] files,LmActivity lmActivity)
    {
        try
        {
            // 上传文件路径
            String filePath = Global.getUploadPath();
            //根据Id获取活动
            LmActivity temp = lmActivityService.selectLmActivityById(lmActivity.getId());
            // 上传并返回新文件名称,拼接图片路径
            StringBuffer sb = new StringBuffer();
            if(EmptyUtils.isNotEmpty(temp.getActivityPimages())){
                 sb.append(temp.getActivityPimages()+",");
            }
            for(int i=0;i<files.length;i++){
                String fileName = FileUploadUtils.upload(filePath, files[i]);
                String url = serverConfig.getUrl() + fileName;
                if(i != files.length-1){
                    sb.append(url+",");
                }else{
                    sb.append(url);
                }
            }
            lmActivity.setActivityPimages(sb.toString());
            return toAjax(lmActivityService.updateLmActivity(lmActivity));
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 审核活动
     */
    @RequiresPermissions("lm:activity:edit")
    @Log(title = "审核活动", businessType = BusinessType.UPDATE)
    @PostMapping("/reviewActivity")
    @ResponseBody
    public AjaxResult reviewActivity(String id)
    {
        LmActivity lmActivity = new LmActivity();
        lmActivity.setId(id);
        lmActivity.setActivityStatus("2");
        lmActivity.setReviewId(ShiroUtils.getSysUser().getLoginName());
        lmActivity.setReviewTime(new Date());
        int num= lmActivityService.updateLmActivity(lmActivity);
        if(num >0){
            //下架通知
            //添加拒绝消息提醒
            LmMessage lmMessage =new LmMessage();
            lmMessage.setMessageUser(lmActivityService.selectLmActivityById(id).getUserId());
            lmMessage.setMessageTitle("活动申通通过通知");
            lmMessage.setMessageContent("恭喜您，活动申请已经通过");
            lmMessage.setMessageType("个人");
            lmMessageService.insertLmMessage(lmMessage);
        }
        return toAjax(num);
    }

    /**
     * 中止活动
     */
    @RequiresPermissions("lm:activity:edit")
    @Log(title = "中止活动", businessType = BusinessType.UPDATE)
    @PostMapping("/stopActivity")
    @ResponseBody
    public AjaxResult stopActivity(String id)
    {
        LmActivity lmActivity = new LmActivity();
        lmActivity.setId(id);
        lmActivity.setActivityStatus("3");
        return toAjax(lmActivityService.updateLmActivity(lmActivity));
    }


    /**
     * 删除活动
     */
    @RequiresPermissions("lm:activity:remove")
    @Log(title = "活动", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(lmActivityService.deleteLmActivityByIds(ids));
    }
}
